import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiaolong
 * @version 1.0
 * @description: TODO
 * @date 2022/2/18 20:40
 */
public class SynchronizedByKey {

    //线程安全
    Map<String,Object> mutexCache = new ConcurrentHashMap<>();


    //工具类
    public void exec(String key, Runnable statement){

        Object mutex4key = mutexCache.computeIfAbsent(key, k -> new Object());
        synchronized (mutex4key){
            try {
                statement.run();
            } finally {
                mutexCache.remove(key);
            }
        }
    }

}
